package tracking.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import tracking.LogUtil;
import tracking.dto.Userdto;

public class Userdao {
	private static final String TAG = "Userdao";
	private Connection conn = null;
	
	/**
	 * Constructor
	 * 
	 * @param conn
	 */
	public Userdao(Connection conn) {
		this.conn = conn;
	}
	
	public ResultSet getAllUser(){
		LogUtil.log(TAG, "NECVN>>>" + "getAllUser");
		ResultSet resultSet = null;
		try {
			String sql = "SELECT * FROM myuser";
			PreparedStatement ps = conn.prepareStatement(sql);
			resultSet = ps.executeQuery();
		} catch (SQLException sqlex) {
			LogUtil.log(TAG, "NECVN>>>" + sqlex.toString());
		}
		return resultSet;
	}
	
	public boolean isCheckUSerOK(Userdto dto){
		try {
			String sql = "SELECT * FROM myuser where userid = ? and password = ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, dto.getUserId());
			ps.setString(2, dto.getPassword());
			ResultSet resultSet = ps.executeQuery();
			if(resultSet!= null && resultSet.first()){
				return true;
			}
			return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}
	
	public boolean isUserIdExist(Userdto dto){
		try {
			String sql = "SELECT * FROM myuser where userid = ?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, dto.getUserId());
			ResultSet resultSet = ps.executeQuery();
			if(resultSet!= null && resultSet.first()){
				return true;
			}
			return false;
			
		} catch (Exception e) {
			e.printStackTrace();
			return true;
		}
	}
	
	public void insertUser(Userdto dto){
		try {
			String sql = "insert into myuser values (?,?)";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, dto.getUserId());
			ps.setString(2, dto.getPassword());
			ps.executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
